﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace _13.WordsCount
{
    class WordsCount
    {
        static void Main()
        {
            List<string> countList = new List<string>();
            try
            {
                using (StreamReader readerCountList = new StreamReader("CountList.txt", System.Text.Encoding.Unicode))
                {
                    string line = readerCountList.ReadLine();
                    while (line != null)
                    {
                        foreach (Match match in Regex.Matches(line, @"[\w*\p{S}*]+"))
                        {
                            countList.Add(match.Value);
                        }
                        line = readerCountList.ReadLine();
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("The list with words to count can not be read.");
            }

            string text = "";
            try
            {
                using (StreamReader readerInput = new StreamReader("Text.txt", System.Text.Encoding.Unicode))
                {
                    string line = readerInput.ReadLine();
                    while (line != null)
                    {
                        text += line + "\r\n";
                        line = readerInput.ReadLine();
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("The text file can not be read.");
            }

            try
            {
                for (int i = 0; i < countList.Count; i++)
                {
                    string line = countList[i];
                    int counter = Regex.Matches(text, "\\b" + line + "\\b").Count;
                    countList.RemoveAt(i);
                    countList.Insert(i, String.Format("{0,3} - {1}", counter, line));
                }
                countList.Sort(new Comparison<string>((x, y) => y.CompareTo(x)));

                using (StreamWriter writer = new StreamWriter("Result.txt"))
                {
                    foreach (var line in countList)
                    {
                        writer.WriteLine(line);
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Error occured during counting words.");
            }
        }
    }
}
